package com.qianfeng.excel.utils;

//
//                            _ooOoo_  
//                           o8888888o  
//                           88" . "88  
//                           (| -_- |)  
//                            O\ = /O  
//                        ____/`---'\____  
//                      .   ' \\| |// `.  
//                       / \\||| : |||// \  
//                     / _||||| -:- |||||- \  
//                       | | \\\ - /// | |  
//                     | \_| ''\---/'' | |  
//                      \ .-\__ `-` ___/-. /  
//                   ___`. .' /--.--\ `. . __  
//                ."" '< `.___\_<|>_/___.' >'"".  
//               | | : `- \`.;`\ _ /`;.`/ - ` : | |  
//                 \ \ `-. \_ __\ /__ _/ .-` / /  
//         ======`-.____`-.___\_____/___.-`____.-'======  
//                            `=---='  
//  
//         .............................................  
//                  佛祖镇楼                  BUG辟易  
//          佛曰:  
//                  写字楼里写字间，写字间里程序员；  
//                  程序人员写程序，又拿程序换酒钱。  
//                  酒醒只在网上坐，酒醉还来网下眠；  
//                  酒醉酒醒日复日，网上网下年复年。  
//                  但愿老死电脑间，不愿鞠躬老板前；  
//                  奔驰宝马贵者趣，公交自行程序员。  
//                  别人笑我忒疯癫，我笑自己命太贱；  
//  


import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.qianfeng.excel.MainApplication;
import com.qianfeng.excel.handler.ImageCellWriteHandler;
import com.qianfeng.excel.listeners.ExcelListener;
import com.qianfeng.excel.listeners.OnDoneListener;
import com.qianfeng.excel.pojo.PersonData;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Calendar;
import java.util.List;
import java.util.Map;

/**
 * Created by Jackiechan on 2022/4/24 16:47
 *
 * @author Jackiechan
 * @version 1.0
 * @since 1.0
 */
public class Utils {
    private static Calendar cal = Calendar.getInstance();

    public static String wxnljqd = "ri";//年龄精确度

    public static long age = 12;//年龄

    public static int getYear() {
        return cal.get(Calendar.YEAR);
    }

    public static int getMonth() {
        return cal.get(Calendar.MONTH);
    }

    public static int getDay() {
        return cal.get(Calendar.DAY_OF_MONTH);
    }

    public static void crateExcel(String tempFile, String dataFile, String imgFile, int sheetIndex, String targetPath, OnDoneListener onDoneListener) {
        String suffix = "jpg";
//        String picPath = imgFile.substring(0, dataFile.lastIndexOf("\\") + 1);
        String picPath = null;
        if (imgFile.contains("/")) {
            picPath = imgFile.substring(0, imgFile.lastIndexOf("/") + 1);
        }else{
            picPath = imgFile.substring(0, imgFile.lastIndexOf(File.separator) + 1);
        }

        System.err.println(picPath);
        //模板文件位置,可以根据实际情况改变,暂时也携带者数据
        //String tempFile = "D:\\Java\\code\\household-statistics\\src\\main\\resources\\a.xlsx";
        //数据文件所在的位置,暂时和模板文件是同一个文件
        // String dataFile="D:\\Java\\code\\household-statistics\\src\\main\\resources\\a.xlsx";
        //创建读取文件的监听器
        ExcelListener excelListener = new ExcelListener();
        //把数据读取出来, 数据放到第二个sheet上
        EasyExcel.read(dataFile, PersonData.class, excelListener).sheet(sheetIndex - 1).headRowNumber(2).doRead();
        //获取到所有的房主数据
        Map<String, PersonData> personDataMap = excelListener.getPersonDataMap();
        //遍历所有的房主
        String finalPicPath = picPath;
        personDataMap.entrySet().forEach((data) -> {
            //拿到每个房主
            PersonData personData = data.getValue();
            StringBuffer stringBuffer = new StringBuffer(personData.getBuildingNum());
            stringBuffer.append("-");
            stringBuffer.append(personData.getDanyuan());
            stringBuffer.append("-");
            stringBuffer.append(personData.getMenhao());
            stringBuffer.append("-");
            stringBuffer.append(personData.getXingming());
            String imageName = stringBuffer.toString();

            try {

                ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
                // BufferedImage bufferImg = ImageIO.read(new File(picPath + "img\\" + imageName + "." + suffix));
                BufferedImage bufferImg = null;
                if (finalPicPath.contains("/")) {
                    bufferImg = ImageIO.read(new File(finalPicPath + "img" + "/" + imageName + "." + suffix));
                } else {
                    bufferImg = ImageIO.read(new File(finalPicPath + "img" + File.separator + imageName + "." + suffix));
                }

                ImageIO.write(bufferImg, suffix, byteArrayOut);
                personData.setZhaopian(byteArrayOut.toByteArray());
            } catch (IOException e) {
                //  e.printStackTrace();
                //   onDoneListener.onFail(imageName+"  没有照片");
            }
            //获取到房子的地址,用于生成文件
            String dizhi = personData.getFangzizonghedizhi();

            //获取到房子中的所有住户
            List<PersonData> zhuhuList = personData.getZhuhuList();
            //目标文件的位置
//            String targetFile = "D:\\Java\\code\\household-statistics\\src\\main\\resources\\" + dizhi +"-"+ personData.getYongtu() +".xlsx";
            String targetFile = targetPath + File.separator + dizhi + "-" + personData.getYongtu() + ".xlsx";
            //先读取模板文件,添加sheet
            try (InputStream fileInputStream = MainApplication.class.getClassLoader().getResourceAsStream(tempFile); ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
                //填充到sheet的数据
                //原模板只有一个sheet，通过poi复制出需要的sheet个数的模板
                XSSFWorkbook workbook = new XSSFWorkbook(fileInputStream);
                //设置产权人的sheet名字
                workbook.setSheetName(0, "产权人-" + personData.getXingming());
                workbook.removeSheetAt(1);
                //创建租户的sheet
                if (zhuhuList != null && zhuhuList.size() > 0) {
                    workbook.setSheetName(1, "住户-" + zhuhuList.get(0).getXingming());
                    for (int i = 1; i < zhuhuList.size(); i++) {
                        //复制住户的sheet模板
                        workbook.cloneSheet(1, "住户-" + zhuhuList.get(i).getXingming());
                    }
                }

                //写到流里
                workbook.write(bos);
                //将模板文件转成字节数组
                byte[] bArray = bos.toByteArray();
                //重新读取到输入流
                InputStream is = new ByteArrayInputStream(bArray);
                //输出文件路径,以前面的模板文件作为来源
                ExcelWriter excelWriter = EasyExcel.write(targetFile).withTemplate(is).registerWriteHandler(new ImageCellWriteHandler()).build();
                //找到产权人的sheet
                WriteSheet writeSheet = EasyExcel.writerSheet(0).build();
                //写入产权人数据
                excelWriter.fill(personData, writeSheet);

                //写入住户的sheet数据
                zhuhuList.forEach(personData1 -> {
                    try {
                        ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
                        StringBuffer stringBuffer1 = new StringBuffer(personData1.getBuildingNum());
                        stringBuffer1.append("-");
                        stringBuffer1.append(personData1.getDanyuan());
                        stringBuffer1.append("-");
                        stringBuffer1.append(personData1.getMenhao());
                        stringBuffer1.append("-");
                        stringBuffer1.append(personData1.getXingming());
                        String imageName1 = stringBuffer1.toString();
                        BufferedImage bufferImg = ImageIO.read(new File(finalPicPath + "img" + File.separator + imageName1 + "." + suffix));
                        ImageIO.write(bufferImg, suffix, byteArrayOut);
                        personData1.setZhaopian(byteArrayOut.toByteArray());
                    } catch (IOException e) {
                        // e.printStackTrace();
                        // onDoneListener.onFail(imageName+"  没有照片");
                    }
                    //找到每个住户的sheet
                    WriteSheet writeSheet2 = EasyExcel.writerSheet("住户-" + personData1.getXingming()).build();
                    //把数据写进去
                    excelWriter.fill(personData1, writeSheet2);
                });
                // 关闭流
                excelWriter.finish();
                workbook.close();
            } catch (IOException e) {
                e.printStackTrace();
                onDoneListener.onFail("excel文件或者导出目录不存在");
            }

        });

        onDoneListener.onSuccess();
    }
}
